/*
 * SupplierManager.java 2012-8-23
 * Copyright(c) 20012-2015 by covidien
 * ALL Rights Reserved.
 */
package com.mvc.base.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.base.model.Supplier;
import com.mvc.framework.dao.HibernateIdUtils;
import com.mvc.framework.model.Auditable;
import com.mvc.portal.service.CUserManager;
import com.mvc.portal.web.ExtendUserController;
import com.mvc.security.model.User;

@Service
public class SupplierManager extends BaseCompanyManager<Supplier, Integer> {
	@Autowired
	private CUserManager	cUserManager;

	public Supplier get(Serializable id) {
		Supplier supplier = (Supplier) super.get(id);
		supplier.setUser(cUserManager.getByObjectId(supplier.getLoginUserId()));
		return supplier;
	}

	public void save(Supplier entity) {
		if (null == entity.getObjectId()) {
			entity.setObjectId(HibernateIdUtils.getUnCacheCustomizeId(getHibernateTemplate().getSessionFactory(), "supplierId"));
		}
		User user = null;
		if (null == entity.getLoginUserId()) {
			user = createUser(entity);
			User exist = cUserManager.checkIfExistsUser(user);
			if (exist != null) {
				throw new RuntimeException("登录名不能重复");
			}
			cUserManager.save(user);
			entity.setLoginUserId(user.getObjectId());
		}
		super.save(entity);
	}

	protected User createUser(Supplier entity) {
		User user = entity.getUser();
		user.setUserName(entity.getName());
		user.setEmail(entity.getEmail());
		user.setType(ExtendUserController.USER_SUPPLIER);
		user.setPassword(entity.getUser().getPassword());
		return user;
	}

	public List<Supplier> getAll() {
		return searchBySql(Supplier.class, "select A from " + Supplier.class.getName() + " A where A.recStatus=? order by A.name",
		        new Object[] { Auditable.REC_STATUS_VALID });
	}

	public Supplier getSupplierByLoginUserId(Integer loginUserId) {
		Supplier example = new Supplier();
		example.setRecStatus(Auditable.REC_STATUS_VALID);
		example.setLoginUserId(loginUserId);
		List<Supplier> list = getHibernateTemplate().findByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
}
